package com.tal.bcc.pad.cloud.coreprogress;

import java.io.IOException;
import java.io.OutputStream;

class ProgressOutputStream extends OutputStream {
    private final OutputStream stream;
    private final ProgressCallback listener;
    private long total;
    private long totalWritten;

    ProgressOutputStream(OutputStream stream, ProgressCallback listener, long total) {
        this.stream = stream;
        this.listener = listener;
        this.total = total;
    }

    public void write(byte[] b, int off, int len) throws IOException {
        this.stream.write(b, off, len);
        if (this.total < 0L) {
            this.listener.onProgressChanged(-1L, -1L, -1.0F);
        } else {
            if (len < b.length) {
                this.totalWritten += (long)len;
            } else {
                this.totalWritten += (long)b.length;
            }

            this.listener.onProgressChanged(this.totalWritten, this.total, (float)this.totalWritten * 1.0F / (float)this.total);
        }
    }

    public void write(int b) throws IOException {
        this.stream.write(b);
        if (this.total < 0L) {
            this.listener.onProgressChanged(-1L, -1L, -1.0F);
        } else {
            ++this.totalWritten;
            this.listener.onProgressChanged(this.totalWritten, this.total, (float)this.totalWritten * 1.0F / (float)this.total);
        }
    }

    public void close() throws IOException {
        if (this.stream != null) {
            this.stream.close();
        }

    }

    public void flush() throws IOException {
        if (this.stream != null) {
            this.stream.flush();
        }

    }
}
